<template>
  <div class="attribute-page">
    <!-- 角色信息 -->
    <div class="character-info">
      <div class="info-row">
        <span class="nickname">{{ nickname || '未知角色' }}</span>
        <span class="combat-power">战力: {{ combatPower || 0 }}</span>
      </div>
      <div class="info-row">
        <span class="level">等级: {{ userLevel || 1 }}</span>
        <span class="realm">境界: {{ realmName || '凡人' }}</span>
      </div>
      <div class="exp-bar">
        <span class="exp-text">经验: {{ userExp || 0 }}/{{ userNeedExp || 100 }}</span>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: userExpPercent + '%' }"></div>
        </div>
      </div>
    </div>

    <!-- 装备槽位模块 -->
    <section class="attribute-section equipment-card">
      <div class="section-header">
        <span class="section-title">装备槽位</span>
        <span v-if="setName" class="set-name">套装: {{ setName }}</span>
      </div>
      <div class="slot-grid">
        <div class="slot-box weapon" @click="openEquipModal('weapon')">
          <div class="slot-label">武器</div>
          <div v-if="equippedWeapon" class="slot-item">
            <span class="item-name">{{ displayEquipmentName(equippedWeapon) }}</span>
            <span class="item-id">ID: {{ equippedWeapon.id || equippedWeapon.equipmentId }}</span>
          </div>
          <div v-else class="slot-empty">空</div>
        </div>
        <div class="slot-box helmet" @click="openEquipModal('helmet')">
          <div class="slot-label">头盔</div>
          <div v-if="equippedHelmet" class="slot-item">
            <span class="item-name">{{ displayEquipmentName(equippedHelmet) }}</span>
            <span class="item-id">ID: {{ equippedHelmet.id || equippedHelmet.equipmentId }}</span>
          </div>
          <div v-else class="slot-empty">空</div>
        </div>
        <div class="slot-box armor" @click="openEquipModal('armor')">
          <div class="slot-label">衣服</div>
          <div v-if="equippedArmor" class="slot-item">
            <span class="item-name">{{ displayEquipmentName(equippedArmor) }}</span>
            <span class="item-id">ID: {{ equippedArmor.id || equippedArmor.equipmentId }}</span>
          </div>
          <div v-else class="slot-empty">空</div>
        </div>
        <div class="slot-box boots" @click="openEquipModal('boots')">
          <div class="slot-label">鞋子</div>
          <div v-if="equippedBoots" class="slot-item">
            <span class="item-name">{{ displayEquipmentName(equippedBoots) }}</span>
            <span class="item-id">ID: {{ equippedBoots.id || equippedBoots.equipmentId }}</span>
          </div>
          <div v-else class="slot-empty">空</div>
        </div>
      </div>
    </section>

    <!-- 选择装备弹窗 -->
    <div v-if="showEquipModal" class="equip-modal-backdrop" @click.self="closeEquipModal">
      <div class="equip-modal">
        <div class="modal-header">
          <span>选择装备（{{ slotLabel(selectedSlot) }}）</span>
          <button class="close-btn" @click="closeEquipModal">×</button>
        </div>
        <div class="modal-list">
          <div v-for="item in selectableEquipments" :key="item.id || item.equipmentId" class="modal-item">
            <div class="item-info">
              <span class="item-name">{{ displayEquipmentName(item) }}</span>
              <span class="item-sub">ID: {{ item.id || item.equipmentId }}</span>
              <span class="item-sub" v-if="item.slot">槽位: {{ slotLabel(item.slot) }}</span>
            </div>
            <button class="equip-btn" @click="equipSelected(item)">装备</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 属性点分配 -->
    <section class="attribute-section">
      <span class="section-title">属性点分配</span>
      <div class="points-info">
        <span class="available-points">
          可用点数: <span class="points-number">{{ availablePoints || 0 }}</span>
        </span>
        <div class="action-buttons">
          <button class="action-btn auto-btn" @click="autoAssign">智能分配</button>
          <button class="action-btn reset-btn" @click="resetPoints" :disabled="!hasChanges">重置</button>
          <button class="action-btn confirm-btn" @click="confirmAssign" :disabled="!hasChanges">确认</button>
        </div>
      </div>

      <!-- 基础属性 -->
      <div v-for="attr in baseAttributeList" :key="attr.key" class="attribute-item">
        <div class="attr-icon" :class="attr.key">{{ attr.icon }}</div>
        <div class="attr-info">
          <span class="attr-name">{{ attr.name }}</span>
          <span class="attr-desc">{{ attr.desc }}</span>
          <div class="attr-value">
            <span class="current-value">{{ attr.total }}</span>
            <span v-if="attr.bonus > 0" class="bonus-value">(+{{ attr.bonus }})</span>
          </div>
        </div>
        <div class="attr-controls">
          <button 
            class="control-btn minus-btn" 
            @click="adjustAttribute(attr.key, -1)"
            :disabled="!tempDistribution[attr.key] || tempDistribution[attr.key] <= 0"
          >-</button>
          <span class="temp-points">{{ tempDistribution[attr.key] || 0 }}</span>
          <button 
            class="control-btn plus-btn" 
            @click="adjustAttribute(attr.key, 1)"
            :disabled="remainingPoints <= 0"
          >+</button>
        </div>
      </div>
    </section>
    
    <!-- 相性加点 -->
    <section class="attribute-section affinity-section">
      <span class="section-title">相性加点</span>
      <div class="points-info">
        <span class="available-points">
          可用相性点: <span class="points-number">{{ availableAffinityPoints || 0 }}</span>
        </span>
        <div class="action-buttons">
          <button class="action-btn reset-btn" @click="resetAffinityPoints" :disabled="!hasAffinityChanges">重置</button>
          <button class="action-btn confirm-btn" @click="confirmAffinityAssign" :disabled="!hasAffinityChanges">确认</button>
        </div>
      </div>

      <!-- 相性属性 -->
      <div v-for="attr in affinityAttributeList" :key="attr.key" class="attribute-item">
        <div class="attr-icon" :class="attr.key">{{ attr.icon }}</div>
        <div class="attr-info">
          <span class="attr-name">{{ attr.name }}</span>
          <span class="attr-desc">{{ attr.desc }}</span>
          <div class="attr-value">
            <span class="current-value">{{ attr.value || 0 }}</span>
          </div>
        </div>
        <div class="attr-controls">
          <button 
            class="control-btn minus-btn" 
            @click="adjustAffinityAttribute(attr.key, -1)"
            :disabled="!tempAffinityDistribution[attr.key] || tempAffinityDistribution[attr.key] <= 0"
          >-</button>
          <span class="temp-points">{{ tempAffinityDistribution[attr.key] || 0 }}</span>
          <button 
            class="control-btn plus-btn" 
            @click="adjustAffinityAttribute(attr.key, 1)"
            :disabled="remainingAffinityPoints <= 0"
          >+</button>
        </div>
      </div>
    </section>

    <!-- 基础属性 -->
    <section class="attribute-section combat-stats">
      <span class="section-title">基础属性</span>
      <div class="stats-grid">
        <div class="stat-item">
          <span class="stat-name">生命值</span>
          <span class="stat-value">{{ attributes.health?.total || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-name">防御力</span>
          <span class="stat-value">{{ attributes.defense?.total || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-name">速度</span>
          <span class="stat-value">{{ attributes.speed?.total || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-name">基础伤害</span>
          <span class="stat-value">{{ attributes.baseDamage?.total || 0 }}</span>
        </div>
      </div>
    </section>

    <!-- 进阶属性 -->
    <section class="attribute-section combat-stats">
      <span class="section-title">进阶属性</span>
      <div class="stats-grid">
        <div class="stat-item">
          <span class="stat-name">伤害加成</span>
          <span class="stat-value">{{ attributes.damageIncrease?.total || 0 }}%</span>
        </div>
        <div class="stat-item">
          <span class="stat-name">伤害减免</span>
          <span class="stat-value">{{ attributes.damageReduction?.total || 0 }}%</span>
        </div>
        <div class="stat-item">
          <span class="stat-name">暴击率</span>
          <span class="stat-value">{{ attributes.critRate?.total || 0 }}%</span>
        </div>
        <div class="stat-item">
          <span class="stat-name">异常抗性</span>
          <span class="stat-value">{{ attributes.abnormalResist?.total || 0 }}%</span>
        </div>
        <div class="stat-item">
          <span class="stat-name">控制成功率</span>
          <span class="stat-value">{{ attributes.controlSuccess?.total || 0 }}%</span>
        </div>
        <div class="stat-item">
          <span class="stat-name">闪避率</span>
          <span class="stat-value">{{ attributes.dodgeRate?.total || 0 }}%</span>
        </div>
        <div class="stat-item">
          <span class="stat-name">命中率</span>
          <span class="stat-value">{{ attributes.hitRate?.total || 0 }}%</span>
        </div>
      </div>
    </section>

    <!-- 境界修炼 -->
    <section class="attribute-section realm-section">
      <span class="section-title">境界修炼</span>
      <div class="realm-info">
        <span class="current-realm">{{ realmName || '凡人' }}</span>
        <div class="realm-progress">
          <span class="progress-text">修炼进度: {{ realmProgress }}%</span>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: realmProgress + '%' }"></div>
          </div>
        </div>
      </div>
      
      <div class="breakthrough-requirements">
        <span class="requirement-title">突破条件</span>
        <span class="requirement-item">等级要求: {{ nextRealm.levelRequirement || 10 }}</span>
        <span class="requirement-item">属性要求: 总属性点 {{ nextRealm.attributeRequirement || 50 }}</span>
      </div>
      
      <button class="breakthrough-btn" @click="breakthrough" :disabled="!canBreakthrough">
        突破境界
      </button>
    </section>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <span class="loading-text">加载中...</span>
    </div>
  </div>
</template>

<script>
import { autoDistributeAttributes, breakthroughRealm } from '@/api/character.js'
import { mapState, mapGetters, mapActions } from 'vuex'

export default {
	data() {
		return {
			// userInfo 和 levelInfo 已移除，改为使用全局 user store
			attributes: {
				// 基础属性
				constitution: { base: 10, bonus: 0, total: 10 },
				strength: { base: 10, bonus: 0, total: 10 },
				agility: { base: 10, bonus: 0, total: 10 },
				// 战斗属性
				health: { base: 100, bonus: 0, total: 100 },
				defense: { base: 10, bonus: 0, total: 10 },
				speed: { base: 10, bonus: 0, total: 10 },
				baseDamage: { base: 10, bonus: 0, total: 10 },
				// 进阶属性
				damageIncrease: { base: 0, bonus: 0, total: 0 },
				damageReduction: { base: 0, bonus: 0, total: 0 },
				critRate: { base: 5, bonus: 0, total: 5 },
				abnormalResist: { base: 0, bonus: 0, total: 0 },
				controlSuccess: { base: 0, bonus: 0, total: 0 },
				dodgeRate: { base: 5, bonus: 0, total: 5 },
				hitRate: { base: 95, bonus: 0, total: 95 },
				// 相性属性
				attack: { value: 0 },
				defense: { value: 0 },
				illusion: { value: 0 },
				// 其他
				availablePoints: 0,
				availableAffinityPoints: 0,
				combatPower: 0
			},
			tempPoints: {
				constitution: 0,
				strength: 0,
				agility: 0
		},
		nextRealm: {
			name: '练气期',
			levelRequirement: 10,
			attributeRequirement: 50
		},
		loading: false,
		showEquipModal: false,
		selectedSlot: ''
		}
	},
	
	computed: {
		// 从全局 user store 获取用户信息
		...mapGetters('user', {
			nickname: 'nickname',
			avatarUrl: 'avatarUrl',
			userLevel: 'level',
			userExp: 'exp',
			userNeedExp: 'needExp',
			userExpPercent: 'expPercent',
			realmName: 'realmName',
			realmDesc: 'realmDesc'
		}),
		
		realmProgress() {
			// 基于等级计算境界进度
			const level = this.userLevel || 1
			const requirement = this.nextRealm.levelRequirement || 10
			return Math.min((level / requirement) * 100, 100)
		},
		
		// 映射 Vuex 状态与计算属性
		...mapState('attribute', {
		tempDistribution: state => state.tempDistribution,
		tempAffinityDistribution: state => state.tempAffinityDistribution,
		availablePoints: state => state.availablePoints,
		availableAffinityPoints: state => state.availableAffinityPoints,
		baseAttributes: state => state.baseAttributes,
		affinityAttributes: state => state.affinityAttributes,
		basicStats: state => state.basicStats,
		advancedStats: state => state.advancedStats,
		combatPower: state => state.combatPower
		}),
		...mapGetters('attribute', {
		storeRemainingPoints: 'remainingPoints',
		storeHasChanges: 'hasTempDistribution',
		storeRemainingAffinityPoints: 'remainingAffinityPoints',
		storeHasAffinityChanges: 'hasTempAffinityDistribution'
		}),
		// 使用 store 的 getters 暴露到本地计算属性
		remainingPoints() {
			return this.storeRemainingPoints
		},
		hasChanges() {
			return this.storeHasChanges
		},
		remainingAffinityPoints() {
			return this.storeRemainingAffinityPoints
		},
		hasAffinityChanges() {
			return this.storeHasAffinityChanges
		},
		baseAttributeList() {
			return [
				{
					key: 'constitution',
					name: '体质',
					desc: '影响生命值和防御力',
					icon: '💪',
					base: this.attributes.constitution?.base || 10,
					bonus: this.attributes.constitution?.bonus || 0,
					total: this.attributes.constitution?.total || 10
				},
				{
					key: 'strength',
					name: '力量',
					desc: '影响攻击力和伤害',
					icon: '⚔️',
					base: this.attributes.strength?.base || 10,
					bonus: this.attributes.strength?.bonus || 0,
					total: this.attributes.strength?.total || 10
				},
				{
					key: 'agility',
					name: '敏捷',
					desc: '影响速度和闪避率',
					icon: '🏃',
					base: this.attributes.agility?.base || 10,
					bonus: this.attributes.agility?.bonus || 0,
					total: this.attributes.agility?.total || 10
				}
			]
		},
		
		affinityAttributeList() {
			return [
				{
					key: 'attack',
					name: '攻',
					desc: '影响攻击效果和伤害',
					icon: '🔥',
					value: this.affinityAttributes?.attack || 0
				},
				{
					key: 'defense',
					name: '守',
					desc: '影响防御效果和减伤',
					icon: '🛡️',
					value: this.affinityAttributes?.defense || 0
				},
				{
					key: 'illusion',
					name: '幻',
					desc: '影响特殊效果和控制',
					icon: '✨',
					value: this.affinityAttributes?.illusion || 0
				}
			]
		},

		// 映射装备模块状态（仅用于装备列表）
		...mapState('equipment', {
		  equipmentList: state => state.equipmentList
		}),
		// 从 attribute store 获取已装备物品和套装名称
		...mapGetters('attribute', {
		  getEquippedItem: 'getEquippedItem',
		  setName: 'getSetName'
		}),
		// 槽位对应的装备
		equippedWeapon() { return this.getEquippedItem('weapon') },
		equippedHelmet() { return this.getEquippedItem('helmet') },
		equippedArmor() { return this.getEquippedItem('armor') },
		equippedBoots() { return this.getEquippedItem('boots') },
		// 弹窗内可选装备列表（已经通过接口参数过滤了类型和已装备的装备）
		selectableEquipments() { 
		  // 前端再次过滤，确保只显示对应类型的装备
		  if (!this.equipmentList || !this.selectedSlot) return []
		  const slotTypeMap = {
		    weapon: 1,
		    armor: 2,
		    helmet: 3,
		    boots: 4
		  }
		  const targetType = slotTypeMap[this.selectedSlot]
		  if (!targetType) return this.equipmentList || []
		  // 后端应该已经过滤了，这里再做一次安全过滤
		  return (this.equipmentList || []).filter(item => item.type === targetType)
		},
		
		canBreakthrough() {
			const level = this.userLevel || 1
			const totalAttributes = this.baseAttributeList.reduce((sum, attr) => sum + attr.total, 0)
			return level >= (this.nextRealm.levelRequirement || 10) && 
				   totalAttributes >= (this.nextRealm.attributeRequirement || 50)
		}
	},
	
	onLoad() {
		this.loadAttributeData()
		// 装备列表改为按需加载，打开弹窗时再加载对应类型的装备
	},
	
	methods: {
		// 载入装备数据（不再预先加载，等打开弹窗时按需加载对应类型的装备）
		async loadEquipmentData() {
		  // 已移除：装备列表改为按需加载，打开弹窗时再加载对应类型的装备
		},
		// 打开装备选择弹窗
		openEquipModal(slot) {
		  this.selectedSlot = slot
		  this.showEquipModal = true
		  // 槽位到装备类型的映射: 1=武器, 2=衣服, 3=头盔, 4=鞋子
		  const slotTypeMap = {
		    weapon: 1,
		    armor: 2,
		    helmet: 3,
		    boots: 4
		  }
		  const equipmentType = slotTypeMap[slot] || 0
		  // 加载对应类型的装备列表，is_select_up=true 会过滤已装备和等级超过玩家等级的装备
		  this.loadEquipmentList({ 
		    type: equipmentType, 
		    is_select_up: true 
		  })
		},
		// 关闭弹窗
		closeEquipModal() { this.showEquipModal = false },
		// 中文槽位名
		slotLabel(slot) {
		  const map = { weapon: '武器', helmet: '头盔', armor: '衣服', boots: '鞋子' }
		  return map[slot] || slot
		},
		// 展示名称
		displayEquipmentName(item) {
		  return item?.name || `装备#${item?.id || item?.equipmentId}`
		},
		// 选择装备并装备到槽位
		// 注意：后端不需要 slot 参数，会根据装备类型自动放到对应槽位
		async equipSelected(item) {
		  if (!item || (!item.id && !item.equipmentId)) {
		    uni.showToast({ title: '请选择有效的装备', icon: 'none' })
		    return
		  }
		  const equipmentId = item.id || item.equipmentId
		  // 后端只需要 equipment_id（int类型），不需要 slot
		  const res = await this.equipItem({ equipmentId })
		  if (res?.success || res?.code === 1 || res?.code === 200) {
		    uni.showToast({ title: res?.message || '装备成功', icon: 'success' })
		    this.showEquipModal = false
		    // 重新加载属性数据以更新装备信息
		    await this.loadAttributeData()
		  } else {
		    uni.showToast({ title: res?.message || res?.msg || '装备失败', icon: 'none' })
		  }
		},
		/**
		 * 加载属性数据（使用简化接口）
		 */
		async loadAttributeData() {
			try {
				this.loading = true
				const roleId = uni.getStorageSync('role_id')
				if (!roleId) {
					console.warn('未找到 role_id，跳过属性加载')
					return
				}
				const resData = await this.loadAttributesSimple(roleId)
				// 使用 store 的返回数据更新本地展示结构
				// 注意：userInfo 和 levelInfo 已改为从全局 user store 读取，不再从属性接口更新
				if (resData) {
					this.attributes = {
						// 基础属性
						constitution: { total: this.baseAttributes.constitution || 0 },
						strength: { total: this.baseAttributes.strength || 0 },
						agility: { total: this.baseAttributes.agility || 0 },
						// 战斗属性
						health: { total: this.basicStats.health || 0 },
						defense: { total: this.basicStats.defense || 0 },
						speed: { total: this.basicStats.speed || 0 },
						baseDamage: { total: this.basicStats.baseDamage || 0 },
						// 进阶属性
						damageIncrease: { total: this.advancedStats.damageIncrease || 0 },
						damageReduction: { total: this.advancedStats.damageReduction || 0 },
						critRate: { total: this.advancedStats.critRate || 0 },
						abnormalResist: { total: this.advancedStats.abnormalResist || 0 },
						controlSuccess: { total: this.advancedStats.controlSuccess || 0 },
						dodgeRate: { total: this.advancedStats.dodgeRate || 0 },
						hitRate: { total: this.advancedStats.hitRate || 0 },
						// 相性属性
						attack: { value: this.affinityAttributes?.attack || 0 },
						defense: { value: this.affinityAttributes?.defense || 0 },
						illusion: { value: this.affinityAttributes?.illusion || 0 },
						// 其他
						availablePoints: this.availablePoints || 0,
						availableAffinityPoints: this.availableAffinityPoints || 0,
						combatPower: this.combatPower || 0
					}
				}
			} catch (error) {
				console.error('加载属性数据失败:', error)
				const errorMsg = error.message || error.toString() || '未知错误'
				uni.showToast({ title: `加载失败: ${errorMsg}`, icon: 'none', duration: 3000 })
			} finally {
				this.loading = false
			}
		},

		/**
		 * 调整属性点（接入 Vuex 临时分配）
		 */
		adjustAttribute(attrKey, change) {
			try {
				this.adjustTempDistribution({ attribute: attrKey, change })
			} catch (err) {
				uni.showToast({ title: err.message || '可分配点数不足', icon: 'none' })
			}
		},

		/**
		 * 调整相性属性点
		 */
		adjustAffinityAttribute(attrKey, change) {
			try {
				this.adjustTempAffinityDistribution({ attribute: attrKey, change })
			} catch (err) {
				uni.showToast({ title: err.message || '可分配相性点不足', icon: 'none' })
			}
		},

		/**
		 * 智能分配属性点
		 */
		async autoAssign() {
			try {
				const roleId = uni.getStorageSync('role_id')
				if (!roleId) {
					uni.showToast({ title: '请先选择角色', icon: 'none' })
					return
				}
				const res = await autoDistributeAttributes({
					roleId,
					availablePoints: this.availablePoints,
					strategy: 'balanced'
				})
				if (res && (res.code === 1 || res.code === 200)) {
					const newDist = { ...(res.data || {}) }
					this.$store.commit('attribute/SET_TEMP_DISTRIBUTION', newDist)
					uni.showToast({ title: '智能分配完成', icon: 'success' })
				} else {
					throw new Error(res?.message || '智能分配失败')
				}
			} catch (error) {
				console.error('智能分配失败:', error)
				uni.showToast({ title: '分配失败', icon: 'error' })
			}
		},

		/**
		 * 重置属性点（接入 Vuex）
		 */
		resetPoints() {
			this.resetTempDistribution()
			uni.showToast({ title: '已重置', icon: 'success' })
		},
		
		/**
		 * 重置相性属性点
		 */
		resetAffinityPoints() {
			this.resetTempAffinityDistribution()
			uni.showToast({ title: '已重置', icon: 'success' })
		},

		/**
		 * 确认分配属性点（接入 Vuex 分配 action）
		 */
		async confirmAssign() {
			if (!this.hasChanges) return
			try {
				const roleId = uni.getStorageSync('role_id')
				if (!roleId) {
					uni.showToast({ title: '请先选择角色', icon: 'none' })
					return
				}
				const res = await this.distributeAttributePoints({
					roleId,
					distribution: this.tempDistribution
				})
				if (res && (res.code === 1 || res.code === 200)) {
					uni.showToast({ title: '分配成功', icon: 'success' })
					await this.loadAttributeData()
					// 装备数据会自动从属性接口更新
				} else {
					throw new Error(res?.message || '分配属性失败')
				}
			} catch (error) {
				console.error('分配属性失败:', error)
				uni.showToast({ title: '分配失败', icon: 'error' })
			}
		},
		
		/**
		 * 确认分配相性属性点
		 */
		async confirmAffinityAssign() {
			if (!this.hasAffinityChanges) return
			try {
				const roleId = uni.getStorageSync('role_id')
				if (!roleId) {
					uni.showToast({ title: '请先选择角色', icon: 'none' })
					return
				}
				const res = await this.distributeAffinityPoints({
					roleId,
					distribution: this.tempAffinityDistribution
				})
				if (res && (res.code === 1 || res.code === 200)) {
					uni.showToast({ title: '相性点分配成功', icon: 'success' })
					await this.loadAttributeData()
				} else {
					throw new Error(res?.message || '分配相性点失败')
				}
			} catch (error) {
				console.error('分配相性点失败:', error)
				uni.showToast({ title: '分配失败', icon: 'error' })
			}
		},

		// 映射 Vuex actions
		...mapActions('attribute', [
			'loadAttributesSimple',
			'adjustTempDistribution',
			'resetTempDistribution',
			'distributeAttributePoints',
			'adjustTempAffinityDistribution',
			'resetTempAffinityDistribution',
			'distributeAffinityPoints'
		]),
		// 映射装备模块 actions（不再调用 loadEquippedItems）
		...mapActions('equipment', [
			'loadEquipmentList',
			'equipItem'
		]),
		
		/**
		 * 突破境界
		 */
		async breakthrough() {
			try {
				if (!this.canBreakthrough) {
					uni.showToast({ title: '突破条件未满足', icon: 'none' })
					return
				}
				const roleId = uni.getStorageSync('role_id')
				if (!roleId) {
					uni.showToast({ title: '请先选择角色', icon: 'none' })
					return
				}
				const res = await breakthroughRealm({ roleId })
				if (res && (res.code === 1 || res.code === 200)) {
					uni.showToast({ title: '突破成功', icon: 'success' })
					await this.loadAttributeData()
				} else {
					throw new Error(res?.msg || '突破失败')
				}
			} catch (error) {
				console.error('突破失败:', error)
				uni.showToast({ title: error.message || '突破失败', icon: 'none' })
			}
		}
	}
}
</script>

<style scoped>
/* ========== 武侠风格属性页面 ========== */
.attribute-page {
  padding: 12px;
  background: linear-gradient(180deg, #e8dcc4 0%, #d4c4a8 100%);
  min-height: 100vh;
  font-family: "STSong", "Noto Serif SC", serif;
  padding-bottom: 80px;
}

.character-info {
  background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%);
  border: 3px solid #4b3a2a;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 12px;
  color: white;
  box-shadow: 0 4px 12px rgba(139, 111, 71, 0.3);
}

.character-info .info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 7.5px;
}

.nickname {
  font-size: 18px;
  font-weight: bold;
}

.level, .realm {
  font-size: 14px;
  opacity: 0.9;
}

.combat-power {
  font-size: 16px;
  font-weight: bold;
  color: #ffd700;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.exp-bar {
  margin-top: 10px;
}

.exp-bar .exp-text {
  font-size: 12px;
  margin-bottom: 5px;
  opacity: 0.9;
}

.progress-bar {
  height: 8px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.progress-bar .progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #d4af37 0%, #ffd700 100%);
  border-radius: 4px;
  transition: width 0.3s ease;
  box-shadow: 0 0 8px rgba(212, 175, 55, 0.5);
}

.attribute-section {
  background: rgba(255, 255, 255, 0.95);
  border: 2px solid #c4a57b;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 12px;
  box-shadow: 0 4px 12px rgba(139, 111, 71, 0.2);
}

.attribute-section .section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.attribute-section .section-title {
  font-size: 16px;
  font-weight: bold;
  color: #4a3c2a;
  position: relative;
  letter-spacing: 1px;
}

.attribute-section .set-name {
  font-size: 13px;
  color: #d4af37;
  font-weight: 700;
  text-shadow: 0 1px 2px rgba(212, 175, 55, 0.3);
  background: linear-gradient(135deg, #d4af37 0%, #ffd700 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.attribute-section .section-title::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 40px;
  height: 3px;
  background: linear-gradient(90deg, #8b6f47 0%, #6b4f3b 100%);
  border-radius: 1.5px;
}

.points-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px;
  background: rgba(139, 111, 71, 0.08);
  border-radius: 8px;
  border: 1px solid #d8c7a3;
}

.available-points {
  font-size: 14px;
  color: #4a3c2a;
  font-weight: 600;
}

.available-points .points-number {
  color: #8b6f47;
  font-weight: bold;
  font-size: 17px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 14px;
  border-radius: 15px;
  font-size: 12px;
  border: 2px solid transparent;
  font-weight: 600;
  transition: all 0.3s ease;
  cursor: pointer;
}

.action-btn.auto-btn {
  background: linear-gradient(135deg, #6b8e67 0%, #5a7a56 100%);
  color: white;
  border-color: #4a6a46;
}

.action-btn.auto-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(107, 142, 103, 0.3);
}

.action-btn.reset-btn {
  background: rgba(139, 111, 71, 0.1);
  color: #6b4f3b;
  border-color: #c4a57b;
}

.action-btn.reset-btn:hover {
  background: rgba(139, 111, 71, 0.2);
}

.action-btn.confirm-btn {
  background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%);
  color: white;
  border-color: #4b3a2a;
}

.action-btn.confirm-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(75, 58, 42, 0.3);
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.attribute-item {
  display: flex;
  align-items: center;
  padding: 12.5px 0;
  border-bottom: 0.5px solid #f0f0f0;
}

.attr-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 14px;
  color: white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.attr-icon.constitution { background: linear-gradient(135deg, #c94a3f 0%, #a83931 100%); }
.attr-icon.strength { background: linear-gradient(135deg, #d4af37 0%, #b8951f 100%); }
.attr-icon.agility { background: linear-gradient(135deg, #6b8e67 0%, #5a7a56 100%); }
.attr-icon.attack { background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%); }
.attr-icon.defense { background: linear-gradient(135deg, #9b7653 0%, #7b5e42 100%); }
.attr-icon.illusion { background: linear-gradient(135deg, #9370db 0%, #7a58c1 100%); }

.attr-info .attr-name {
  font-size: 14px;
  font-weight: bold;
  color: #4a3c2a;
  margin-bottom: 4px;
}

.attr-info .attr-desc {
  font-size: 11px;
  color: #8b6f47;
}

.attr-value {
  font-size: 12px;
  color: #6b4f3b;
  margin-top: 4px;
}

.attr-value .current-value { color: #4a3c2a; font-weight: bold; }
.attr-value .bonus-value { color: #6b8e67; margin-left: 5px; }

.attr-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.control-btn {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: 2px solid transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.control-btn.minus-btn { 
  background: rgba(139, 111, 71, 0.1); 
  color: #999; 
  border-color: #d8c7a3;
}
.control-btn.minus-btn:not(:disabled) { 
  background: linear-gradient(135deg, #c94a3f 0%, #a83931 100%); 
  color: white; 
  border-color: #9b3028;
}
.control-btn.minus-btn:not(:disabled):hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(201, 74, 63, 0.3);
}
.control-btn.plus-btn { 
  background: rgba(139, 111, 71, 0.1); 
  color: #999; 
  border-color: #d8c7a3;
}
.control-btn.plus-btn:not(:disabled) { 
  background: linear-gradient(135deg, #6b8e67 0%, #5a7a56 100%); 
  color: white; 
  border-color: #4a6a46;
}
.control-btn.plus-btn:not(:disabled):hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(107, 142, 103, 0.3);
}
.control-btn:disabled { 
  opacity: 0.4; 
  cursor: not-allowed;
}

.temp-points {
  min-width: 24px;
  text-align: center;
  font-size: 13px;
  color: #8b6f47;
  font-weight: bold;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.stat-item {
  padding: 12px;
  background: rgba(248, 246, 241, 0.8);
  border: 1px solid #d8c7a3;
  border-radius: 8px;
  text-align: center;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(139, 111, 71, 0.15);
}

.stat-name { font-size: 12px; color: #8b6f47; margin-bottom: 5px; font-weight: 600; }
.stat-value { font-size: 15px; font-weight: bold; color: #4a3c2a; }

.realm-info { text-align: center; margin-bottom: 15px; }
.current-realm { font-size: 17px; font-weight: bold; color: #8b6f47; margin-bottom: 10px; letter-spacing: 1px; text-shadow: 0 1px 2px rgba(139, 111, 71, 0.2); }
.realm-progress { margin-bottom: 10px; }
.progress-text { font-size: 12px; color: #6b4f3b; margin-bottom: 6px; font-weight: 600; }
.progress-bar { height: 10px; background-color: rgba(139, 111, 71, 0.15); border-radius: 5px; overflow: hidden; border: 1px solid #d8c7a3; }
.progress-bar .progress-fill { height: 100%; background: linear-gradient(90deg, #8b6f47 0%, #6b4f3b 100%); border-radius: 5px; transition: width 0.3s ease; box-shadow: 0 0 8px rgba(139, 111, 71, 0.4); }

.breakthrough-requirements { background: rgba(248, 246, 241, 0.8); border: 1px solid #d8c7a3; border-radius: 8px; padding: 12px; margin-bottom: 12px; }
.requirement-title { font-size: 13px; font-weight: bold; color: #4a3c2a; margin-bottom: 8px; letter-spacing: 0.5px; }
.requirement-item { font-size: 12px; color: #6b4f3b; margin-bottom: 5px; }

.breakthrough-btn { width: 100%; padding: 12px; border-radius: 15px; border: 2px solid #4b3a2a; background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%); color: white; font-size: 14px; font-weight: bold; cursor: pointer; transition: all 0.3s ease; }
.breakthrough-btn:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(75, 58, 42, 0.3); }
.breakthrough-btn:disabled { background: #d0d0d0; border-color: #999; color: #666; cursor: not-allowed; }

.loading { display: flex; justify-content: center; align-items: center; height: 100px; }
.loading-text { font-size: 14px; color: #8b6f47; font-weight: 600; }

/* 装备槽位卡片与弹窗样式 - 武侠风格 */
.equipment-card .slot-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.slot-box { border: 2px solid #d8c7a3; border-radius: 10px; padding: 12px; background: rgba(248, 246, 241, 0.8); display: flex; flex-direction: column; gap: 6px; align-items: flex-start; cursor: pointer; transition: all 0.3s ease; }
.slot-box:hover { border-color: #8b6f47; background: rgba(255, 255, 255, 0.9); transform: translateY(-2px); box-shadow: 0 3px 10px rgba(139, 111, 71, 0.2); }
.slot-box .slot-label { font-size: 12px; color: #8b6f47; font-weight: 600; }
.slot-box .slot-item { display: flex; flex-direction: column; gap: 4px; }
.slot-box .item-name { font-weight: 600; color: #4a3c2a; font-size: 13px; }
.slot-box .item-id { font-size: 11px; color: #8b6f47; }
.slot-box .slot-empty { width: 100%; height: 40px; border: 2px dashed #d8c7a3; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: #c4a57b; font-weight: 600; }

.equip-modal-backdrop { position: fixed; left: 0; top: 0; right: 0; bottom: 0; background: rgba(75, 58, 42, 0.6); display: flex; align-items: center; justify-content: center; z-index: 1000; backdrop-filter: blur(4px); }
.equip-modal { width: 90%; max-width: 420px; background: rgba(248, 246, 241, 0.98); border: 3px solid #8b6f47; border-radius: 15px; box-shadow: 0 10px 40px rgba(139, 111, 71, 0.5); overflow: hidden; }
.modal-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 15px; border-bottom: 2px solid #c4a57b; background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%); color: white; }
.modal-header span { font-weight: bold; letter-spacing: 1px; }
.close-btn { border: 2px solid rgba(255, 255, 255, 0.3); background: rgba(255, 255, 255, 0.2); color: white; border-radius: 50%; width: 30px; height: 30px; cursor: pointer; font-size: 18px; transition: all 0.3s ease; }
.close-btn:hover { background: rgba(255, 255, 255, 0.3); border-color: rgba(255, 255, 255, 0.5); }
.modal-list { max-height: 60vh; overflow: auto; padding: 12px; display: flex; flex-direction: column; gap: 10px; background: rgba(255, 255, 255, 0.5); }
.modal-item { display: flex; align-items: center; justify-content: space-between; border: 1px solid #d8c7a3; border-radius: 8px; padding: 10px; background: rgba(255, 255, 255, 0.9); transition: all 0.3s ease; }
.modal-item:hover { border-color: #8b6f47; background: rgba(255, 255, 255, 1); transform: translateX(2px); }
.modal-item .item-info { display: flex; flex-direction: column; gap: 3px; }
.modal-item .item-name { font-weight: 600; color: #4a3c2a; }
.modal-item .item-sub { font-size: 12px; color: #8b6f47; }
.equip-btn { background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%); color: #fff; border: 2px solid #4b3a2a; padding: 6px 12px; border-radius: 8px; cursor: pointer; font-weight: 600; transition: all 0.3s ease; }
.equip-btn:hover { transform: translateY(-1px); box-shadow: 0 2px 8px rgba(75, 58, 42, 0.3); }
</style>